package com.example.yt_app.Fragment.LoginFragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;

import com.example.yt_app.Activity.FragmentThreeActivity;


import com.example.yt_app.AppManager;
import com.example.yt_app.Fragment.BaseFragment.BaseFragment;
import com.example.yt_app.Interface.YT_HttpBinService;
import com.example.yt_app.R;
import com.example.yt_app.Urils.AESUtils3;
import com.example.yt_app.Urils.State;
import com.example.yt_app.bean.BaseResponse;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by dell on 2021/7/15.
 */

@SuppressWarnings("ALL")
public class PasswordFragment extends BaseFragment {
    private Unbinder unbinder;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    /**用户与密码*/
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.username_et)
    EditText username_et;
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.password_et)
    EditText password_et;
    /**忘记密码*/
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.forget_user)
    TextView forget_user;
    /**登录*/
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.login_bt)
    Button login_bt;
    /**密码可看*/
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.eye)
    ImageView eye;
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    @BindView(R.id.Buttonc_ok)
    CheckBox buttonc_ok;

    String getMag;
    private String mTitle = "";
    private long downTime = 0;//Button被按下时的时间
    private long thisTime = 0;
    // 两次点击按钮之间的点击间隔不能少于1000毫秒

    /*端口链接*/
    @SuppressWarnings({"AlibabaLowerCamelCaseVariableNaming", "AlibabaCommentsMustBeJavadocFormat"})
    Retrofit YT_retrofit =  new Retrofit
            .Builder()
            .addConverterFactory(GsonConverterFactory.create())//添加转换器
            .baseUrl("http://8.129.133.124:8200/")
            .build();
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    YT_HttpBinService yt_httpBinService =YT_retrofit.create(YT_HttpBinService.class);

    @Override
    protected void setListener() {
        //给CheckBox设置事件监听
        buttonc_ok.setOnCheckedChangeListener((buttonView, isChecked) -> {
            // TODO Auto-generated method stub
            State.READ_1 = isChecked;
        });
        Login_btn();

    }
    /**
     * TODO RX思维
     * */
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    public void RxAsync(){
        /*
         * TODO RX思维
         * */
        Observable.just(YT_retrofit)
                .subscribe(new Observer<Retrofit>() {
                    /*订阅成功*/
                    @Override
                    public void onSubscribe(@NotNull Disposable d) {
                        State.tel = username_et.getText().toString();
                        State.pad = password_et.getText().toString();
                        State.pad = AESUtils3.encryptSalt(State.pad);
                        //返回状态
                        if (State.READ_1){
                            //工作
                            postAsync();
                        }
                        else {
                            showMessage("请勾选阅读条例");
                        }
                    }
                    /*上层给我的相应*/
                    @Override
                    public void onNext(@NotNull Retrofit retrofit) {

                    }
                    /*连接思维发生异常*/
                    @Override
                    public void onError(@NotNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    /**
     * 功能：手机请求接口数据的（异步请求）
     * 作用：验证登录数据是否正确
     * 注释：现在主流常用是异步
     * */
    public void postAsync(){

        Call<BaseResponse> call = yt_httpBinService.login(State.tel, State.pad);
        call.enqueue(new retrofit2.Callback<BaseResponse>() {
            @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
            @Override
            public void onResponse(@NotNull retrofit2.Call<BaseResponse> call, @NotNull retrofit2.Response<BaseResponse> response) {
                BaseResponse baseResponse = response.body();
                assert baseResponse != null;
                getMag = baseResponse.getMsg();
                State.LOGIN = baseResponse.getSuccess();

                if (State.LOGIN == true ){
                    Intent Intent = new Intent(getActivity(), FragmentThreeActivity.class);
                    startActivity(Intent);
                    //PopupActivity.showPopup(Gravity.TOP, ViewGroup.LayoutParams.MATCH_PARENT, widthAndHeight[1] / 4, R.style.TopAnimation);
                    showMessage("登录成功");
                }else {
                    showMessage(getMag);
                }

            }
            @Override
            public void onFailure(retrofit2.Call<BaseResponse> call, Throwable t) {
            }
        });

    }

    /**
     * 功能：消息通知栏
     * 作用：通知用户现在的进程
     *
     * */
    @SuppressWarnings("AlibabaRemoveCommentedCode")
    @Override
    public void showMessage(String message) {
        /*
         * 线程里面需要使用到
         * Looper.prepare();
         * Looper.loop();
         * */
        Toast.makeText(getActivity(),message,Toast.LENGTH_SHORT).show();
    }
    /**
     * 设置登录的点击事件
     * */
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    public void Login_btn(){
        login_bt.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                downTime = event.getDownTime(); //手指按下时间
                thisTime = event.getEventTime();
                switch (event.getAction()) {

                    case MotionEvent.ACTION_UP: //手指抬起
                        if (thisTime - downTime > State.MIN_CLICK_DELAY_TIME ){
                            RxAsync();
                        }
                        //短按事件
                        break;
                    default:break;
                }
                return false;
            }
        });
    }


    /**
     * 点击事件
     * */
    @SuppressWarnings("AlibabaSwitchStatement")
    @OnClick({R.id.eye, R.id.login_bt})
    public void onClick(View v) {
        //noinspection AlibabaSwitchStatement
        switch (v.getId()){
            /**
             *  密码保密
             * */
            case R.id.eye:
                if(State.LOOK  == false){
                    password_et.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    eye.setImageResource(R.mipmap.eye_1);
                    State.LOOK = true;
                }else{
                    password_et.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    State.LOOK = false;
                    eye.setImageResource(R.mipmap.eye);
                }
                break;
        }
    }


}
